package com.shycloud.mido.homework.service.impl;

import com.shycloud.mido.member.api.feign.RemoteMemberService;
import com.shycloud.mido.member.api.vo.TeacherVO;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.JsonObject;
import com.joy.zebra.common.push.JPushUtils;
import com.qiniu.common.QiniuException;
import com.shycloud.common.minio.service.MinioTemplate;
import com.shycloud.mido.common.api.constants.ShoppingStockConstants;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.common.util.NetworkUtil;
import com.shycloud.mido.common.util.SnowFlakeUtil;
import com.shycloud.mido.homework.api.entity.MidoHomeworkMain;
import com.shycloud.mido.homework.api.entity.ZebraHomeworkAssist;
import com.shycloud.mido.homework.api.enums.JPushCodeEnum;
import com.shycloud.mido.homework.api.vo.ZebraHomeworkAssistVO;
import com.shycloud.mido.homework.mapper.MidoHomeworkMainMapper;
import com.shycloud.mido.homework.mapper.ZebraHomeworkAssistMapper;
import com.shycloud.mido.homework.service.ZebraHomeworkAssistService;
import com.shycloud.mido.member.api.entity.MsgMain;
import com.shycloud.mido.member.api.entity.MsgMemberInfo;
import com.shycloud.mido.member.api.feign.RemotePushService;
import lombok.AllArgsConstructor;

/**
 * @author nianhua.jiang
 */
@Service
@AllArgsConstructor
public class ZebraHomeworkAssistServiceImpl extends ServiceImpl<ZebraHomeworkAssistMapper, ZebraHomeworkAssist> implements
		ZebraHomeworkAssistService {


	/** 作业辅导模块 mapper */
	private ZebraHomeworkAssistMapper assistMapper;
	/** 作业模块 mapper */
	private MidoHomeworkMainMapper mainMapper;
	/** 七牛工具类 */
	private MinioTemplate minioTemplate;

	/** 推送 feign service */
	private RemotePushService remotePushService;
	/** 用户模块 feign */
	private RemoteMemberService remoteMemberService;
	/** 七牛云存放录音视频文件的 CDN 域名 */
	private static final String QI_NIU_ASSIST_CDN = "http://assist.joymido.com/";

	private static Log logger = LogFactory.getLog(ZebraHomeworkAssistServiceImpl.class);

	/**
	 * 保存作业辅导
	 *
	 * @param assist
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2021/1/5 9:38
	 **/
	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public String saveAssist(ZebraHomeworkAssist assist) {

		if (assist.getMeasureIndex() == -1) {
			assistMapper.delete(new QueryWrapper<ZebraHomeworkAssist>()
					.eq(ZebraHomeworkAssist.COL_HOMEWORK_ID, assist.getHomeworkId())
					.eq(ZebraHomeworkAssist.COL_MEASURE_INDEX, -1));
		}

		//创建主键
		Integer machineId = ShoppingStockConstants.getConsistentHash(NetworkUtil.getHostIp());
		long assistId = new SnowFlakeUtil(1, machineId).nextId();

		assist.setId(assistId);
		//先插入单条作业模块
		assistMapper.insert(assist);

		//更新作业是否辅导状态
		Long homeworkId = assist.getHomeworkId();
		MidoHomeworkMain midoHomeworkMain = mainMapper.selectById(homeworkId);
		midoHomeworkMain.setIsHelp("1");
		mainMapper.updateById(midoHomeworkMain);

		// 推送自定义消息

		//通过 studentId 获取 regId
		String regId = mainMapper.getRegIdByStudentId(midoHomeworkMain.getStudentId());
		//
		String memberId = mainMapper.getMemberIdByStudentId(midoHomeworkMain.getStudentId());

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

		String startDateStr = formatter.format(midoHomeworkMain.getStartDate());

		if (regId != null) {

			JsonObject jsonObject = new JsonObject();

			jsonObject.addProperty(
					midoHomeworkMain.getGroupId().toString() + "_" + midoHomeworkMain.getPlayingMode() + "_" + startDateStr,
					midoHomeworkMain.getId().toString());

			// 推送隐式消息显示红点
			JPushUtils.sendJMessage(JPushCodeEnum.J_PUSH_TEACHER_ASSIST_HOMEWORK.getType(), regId, jsonObject);
			// 推送消息-即时
			JPushUtils.sendJPush("作业被点评", "老师刚刚点评了你的作业，快来看看吧", regId);
			// 推送消息告知APP请求接口
			JPushUtils.sendJMessage(JPushCodeEnum.J_PUSH_APP_HOMEPAGE_VIEW.getType(), regId, "告知APP请求 getMsgApp 接口");
			// 新增消息
			//String msgId = addMsg("作业被点评", "老师刚刚点评了你的作业，快来看看吧", regId, "", "", "2");
			String msgId = "homework_assist";
			// 发送消息
			MsgMemberInfo msgMemberInfo = new MsgMemberInfo();
			msgMemberInfo.setMsgId(msgId);
			msgMemberInfo.setFromId("sys");
			msgMemberInfo.setToId(memberId);
			msgMemberInfo.setCreateTime(LocalDateTime.now());
			msgMemberInfo.setDelFlag(CommonConstants.STATUS_NORMAL);

			//构建推送响应体
			JsonObject jsonObject2 = new JsonObject();
			//获取教师信息
			TeacherVO teacherVO = remoteMemberService.getTeacherInfoFeign(midoHomeworkMain.getTeacherId());
			//学生头像
			jsonObject2.addProperty("teacherHeader", teacherVO.getAvatar());

			jsonObject2.addProperty("teacherImId", teacherVO.getImId());

			jsonObject2.addProperty("teacherMemberShowName", teacherVO.getTeacherMemberShowName());

			String classroomId = remoteMemberService.getClassroomId(midoHomeworkMain.getTeacherId(), midoHomeworkMain.getStudentId());
			//教师ID
			jsonObject2.addProperty("teacherId", midoHomeworkMain.getTeacherId());
			//班级ID
			jsonObject2.addProperty("classroomId", classroomId);
			//点评作业的作业时间
			jsonObject2.addProperty("startDate", startDateStr);

			msgMemberInfo.setHomeworkData(jsonObject2.toString());

			remotePushService.sendMsg(msgMemberInfo);

		} else {
			logger.error("目标用户 regId 不存在，无法执行消息推送程序");
		}

		return String.valueOf(assistId);
	}

	/**
	 * 删除作业辅导
	 *
	 * @param assistId
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2021/1/5 9:38
	 **/
	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public Boolean delAssist(String assistId) {

		//获取音频/视频文件
		ZebraHomeworkAssist zebraHomeworkAssist = assistMapper.selectById(Long.parseLong(assistId));

		if (zebraHomeworkAssist == null) {
			throw new BusinessException("此作业辅导不存在，删除失败！");
		}

		//语音文件地址
		String voiceUrl = zebraHomeworkAssist.getVoiceUrl();
		//视频文件地址
		String videoUrl = zebraHomeworkAssist.getVideoUrl();

		//删除作业辅导信息
		if (assistMapper.deleteById(Long.parseLong(assistId)) == 1) {
			try {
				//删除七牛云文件
				if (StringUtils.isNotBlank(voiceUrl) && voiceUrl.startsWith(QI_NIU_ASSIST_CDN)) {

					minioTemplate.delete("zebra-homework-assist", voiceUrl.replace(QI_NIU_ASSIST_CDN, ""));

				}
				if (StringUtils.isNotBlank(videoUrl) && videoUrl.startsWith(QI_NIU_ASSIST_CDN)) {
					minioTemplate.delete("zebra-homework-assist", videoUrl.replace(QI_NIU_ASSIST_CDN, ""));
				}
			} catch (QiniuException e) {
				e.printStackTrace();
			}
		}

		return true;

	}

	/**
	 * 获取教师辅导情况
	 *
	 * @param homeworkId
	 * @return java.util.List<com.shycloud.mido.homework.api.entity.ZebraHomeworkAssist>
	 * @author nianhua.jiang
	 * @date 2021/1/5 9:36
	 **/
	@Override
	public List<ZebraHomeworkAssistVO> getAssist(String homeworkId) {

		List<ZebraHomeworkAssist> assistList = assistMapper
				.selectList(new QueryWrapper<ZebraHomeworkAssist>().eq("homework_id", homeworkId));

		List<ZebraHomeworkAssistVO> resList = assistList.stream().map(x -> {
			ZebraHomeworkAssistVO zebraHomeworkAssistVO = new ZebraHomeworkAssistVO();
			BeanUtils.copyProperties(x, zebraHomeworkAssistVO);
			return zebraHomeworkAssistVO;
		}).collect(Collectors.toList());

		for (ZebraHomeworkAssistVO zebra : resList) {
			if (zebra.getCreateTime().plusDays(30).isBefore(LocalDateTime.now())) {
				zebra.setIsExpire("1");
			} else {
				zebra.setIsExpire("0");
			}
		}

		return resList;
	}

	private String addMsg(String title, String message, String regId, String pushRespCode, String pushRespMsg, String triggerTo) {

		MsgMain msgMain = new MsgMain();
		//给【1-教师 2-学生】发送
		msgMain.setTriggerTo(triggerTo);
		//来自师生绑定/解绑 - 系统自动推送
		msgMain.setTriggerFrom("0");
		//消息下发的场合：作业点评
		msgMain.setPoint("6");
		//不可修改
		msgMain.setModify("0");
		//自动推送
		msgMain.setMode("1");
		//个人
		msgMain.setRangeType("1");
		//有效数据
		msgMain.setDelFlag("0");
		//创建时间
		msgMain.setCreateTime(LocalDateTime.now());
		//消息类型：文本
		msgMain.setMsgType("0");
		//发送时间
		msgMain.setActualPubDatetime(LocalDateTime.now());
		//创建人-> 系统
		msgMain.setCreateUser("sys");
		//消息内容
		msgMain.setMessage(message);
		//发布时间
		msgMain.setPubDatetime(LocalDateTime.now());
		//极光推送唯一ID
		msgMain.setPushId(regId);
		//极光推送返回 code
		msgMain.setPushRespCode(pushRespCode);
		//极光推送返回 msg
		msgMain.setPushRespMsg(pushRespMsg);
		//TODO 推送成功
		msgMain.setPushStatus("0");
		//推送时间
		msgMain.setPushTime(LocalDateTime.now());
		//标题
		msgMain.setTitle(title);
		//系统消息
		msgMain.setType("0");

		return (String) remotePushService.addMsg(msgMain).getData();
	}

}
